package org.hxzon.demo.nioclient.apps.echo;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.hxzon.demo.juntai.csserver.server.Util;
import org.hxzon.demo.nioserver.apps.echo.Config;
import org.hxzon.nioclient.NioClient;
import org.hxzon.nioclient.RequestQueue;
import org.hxzon.nioclient.ResponseQueue;
import org.hxzon.nioclient.impl.LengthRequestQueueImpl;
import org.hxzon.nioclient.impl.LengthResponseQueueImpl;
import org.hxzon.nioclient.impl.NioClientImpl;
import org.hxzon.nioserver.BufferFactory;
import org.hxzon.nioserver.impl.DumbBufferFactory;
import org.hxzon.util.Console;
import org.hxzon.util.Console.ConsoleListener;

public class DemoClient {

    public static void main(String[] args) throws IOException {
        BufferFactory bufferFactory = new DumbBufferFactory();
        RequestQueue reqQueue = new LengthRequestQueueImpl(bufferFactory);
        ResponseQueue resQueue = new LengthResponseQueueImpl(bufferFactory);
        final NioClient nioClient = new NioClientImpl(Config.port, reqQueue, resQueue);
        nioClient.start();
        //
        final Console console = new Console();
        console.setConsoleListener(new ConsoleListener() {
            public void listen(String m, Console console) {
                try {
                    if ("quit".equals(m)) {
                        console.stopListen();
                        nioClient.stop();
                        return;
                    } else if ("test long".equals(m)) {
                        ByteBuffer bufSend = ByteBuffer.allocate(1024 * 100);
                        while (bufSend.position() < 1024 * 100) {
                            bufSend.put("a".getBytes(Config.encoding));
                        }
                        nioClient.request(bufSend);
                    } else {
                        byte[] bytes = m.getBytes(Config.encoding);
                        ByteBuffer bufSend = ByteBuffer.allocate(1024 * 100);
                        bufSend.put(bytes);
                        nioClient.request(bufSend);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        console.startListen();
        //
        new Thread() {
            public void run() {
                while (console.isListen()) {
                    ByteBuffer response = nioClient.nextResponse();
                    if (response != null) {
                        String str = Util.readString(response);
                        Util.println("server response:" + str);
                    }
                }
            }
        }.start();
    }
}
